<template>
  <div class="user-info-head">
    <el-dialog
      :title="title"
      v-model="open"
      width="1200px"
      append-to-body
      @close="closeDialog"
    >
      <el-row>
        <el-col :xs="24" :md="12" class="cropper-col">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
          />
        </el-col>
        <el-col :xs="24" :md="12" class="preview-col">
          <div class="avatar-upload-preview">
            <img :src="options.previews.url" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row class="controls-row" justify="space-between">
        <el-col :span="2">
          <el-upload
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <el-button>
              选择
              <el-icon class="el-icon--right"><Upload /></el-icon>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :span="12" class="text-right">
          <el-button icon="Plus" @click="changeScale(1)" />
          <el-button icon="Minus" @click="changeScale(-1)" />
          <el-button icon="RefreshLeft" @click="rotateLeft" />
          <el-button icon="RefreshRight" @click="rotateRight" />
        </el-col>
        <el-col :span="4" class="text-right">
          <el-button type="primary" @click="uploadImg">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, getCurrentInstance } from "vue";
import "vue-cropper/dist/index.css";
import { VueCropper } from "vue-cropper";
import { ElMessage } from "element-plus";
import { uploadFiles } from "@/api/business/upload";
import { useUserStore } from "@/store/modules/user";
import { insertPhoto, personalphotos } from "@/api/business/egg";

const props = defineProps({
  visiable: {
    type: Boolean,
    required: true,
    default: false,
  },
  donorId: {
    type: String,
    required: true,
    default: "",
  },
});

const emit = defineEmits(["closeDialog"]);

const userStore = useUserStore();
const { proxy } = getCurrentInstance();

const open = ref(false);
const title = ref("修改个人形象照");

const options = reactive({
  img: "",
  autoCrop: true,
  autoCropWidth: 460,
  autoCropHeight: 580,
  fixedBox: true,
  outputType: "png",
  filename: "avatar",
  previews: {},
});

function requestUpload() {}

function rotateLeft() {
  proxy.$refs.cropper.rotateLeft();
}

function rotateRight() {
  proxy.$refs.cropper.rotateRight();
}

function changeScale(num) {
  num = num || 1;
  proxy.$refs.cropper.changeScale(num);
}

function beforeUpload(file) {
  if (!file.type.startsWith("image/")) {
    ElMessage.error("文件格式错误，请上传图片类型，如：JPG，PNG 后缀的文件。");
    return false;
  }
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    options.img = reader.result;
    options.filename = file.name;
  };
  return false;
}

function uploadImg() {
  proxy.$refs.cropper.getCropBlob((data) => {
    const formData = new FormData();
    formData.append("files", data, options.filename);
    const uploadUrl = `/business/photo/uploads?username=${userStore.name}`;
    uploadFiles(formData, uploadUrl).then((response) => {
      options.img = response.urls;
      updateForm({ photoUrls: response.urls, basicId: props.donorId });
    });
  });
}

function updateForm(form) {
  insertPhoto(form).then((resp) => {
    if (resp.code === 200) {
      ElMessage.success("上传成功");
      closeDialog();
    } else {
      ElMessage.error("上传失败");
    }
  });
}

function realTime(data) {
  options.previews = data;
}

function closeDialog() {
  emit("closeDialog");
}

watch(
  () => props.visiable,
  (val) => {
    open.value = val;
    if (val) {
      personalphotos({ donorId: props.donorId }).then((res) => {
        options.img = res.rows.length > 0 ? res.rows[0].photoUrl : "";
      });
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.user-info-head {
  position: relative;
  display: inline-block;
  height: 580px;

  &:hover::after {
    content: "+";
    position: absolute;
    inset: 0;
    color: #eee;
    background: rgba(0, 0, 0, 0.5);
    font-size: 24px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    cursor: pointer;
    line-height: 110px;
  }
}

.cropper-col,
.preview-col {
  height: 580px;
}

.avatar-upload-preview {
  width: 460px;
  height: 580px;
  img {
    width: 100%;
    height: 100%;
  }
}

.controls-row {
  align-items: center;
}
</style>
